#include <xp/bas/stdio.h>
#include <xp/bas/sysapi.h>
#include <xp/bas/string.h>

#ifdef __linux
#include <mcheck.h>
#endif

void xxx_trim_unix_path (xp_char_t* pp)
{
	xp_char_t* p, * q; 

	for (p = pp; p[0]; p++) {
		if (p[0] == XP_CHAR('/')) {
			if (p[1] == XP_CHAR('/')) {
				for (q = p; q[0] == XP_CHAR('/'); q++) ;
				xp_strcpy (&p[1], q); p--;
			}
			else if ((p[1] == XP_CHAR('.') && p[2] == XP_CHAR('.')) &&
			         (p[3] == XP_CHAR('/') || p[3] == XP_CHAR('\0'))) {
				if (p == pp && p[0] == XP_CHAR('/')) {
					xp_strcpy (p, &p[3]);
					if (*pp == XP_CHAR('\0')) 
						xp_strcpy (pp, XP_TEXT("/"));
				}
				else {
					for (q = p - 1; q >= pp && *q != XP_CHAR('/'); q--) ;

					if (q[0] == XP_CHAR('/') && 
					    xp_strcmpn(q, XP_TEXT("/../"), 4) &&
					    !(&q[-1] > pp && q[-1] == XP_CHAR('/'))) {

						xp_strcpy (q, &p[3]);
						if (*pp == XP_CHAR('\0'))
							xp_strcpy (pp, XP_TEXT("/"));
						p = q - 1;
					}
				}
			}
			/*
			 *    /etc/./magic ---> /etc/magic
			 */
			else if (p[1] == XP_CHAR('.')) {
				if (p == pp) {
					if (p[2] == XP_CHAR('/')) {
						xp_strcpy (p, &p[2]); p--;
					}
					else if (p[2] == XP_CHAR('\0')) {
						p[1] = XP_CHAR('\0');
						break;
					}
				}
				else {
					if (p[2] == XP_CHAR('/') || p[2] == XP_CHAR('\0')) {
						xp_strcpy (p, &p[2]); p--;
					}
				}
			}
			else if (p != pp && p[1] == XP_CHAR('\0')) {
				*p = XP_CHAR('\0');
				break;
			}
		}
	}
}

int xp_main (int argc, xp_char_t* argv[])
{
//	xp_char_t buf[XP_PATH_MAX + 1];
	xp_char_t buf[20];

#ifdef __linux
	mtrace ();
#endif

	if (argc != 2) {
		xp_fprintf (xp_stderr, XP_TEXT("usage: %s path\n"), argv[0]);
		return -1;
	}

	xp_printf (XP_TEXT("source: [%s]\n"), argv[1]);

/*
	if (xp_trimpath(argv[1], argv[1], xp_strsize(argv[1])) == (xp_size_t)-1) {
		xp_fprintf (xp_stderr, XP_TEXT("cannot trim %s\n"), argv[1]);
		return -1;
	}

	xp_printf (XP_TEXT("result: [%s]\n"), argv[1]);
*/

	if (xp_trimpath(argv[1], buf, xp_countof(buf)) == (xp_size_t)-1) {
		xp_fprintf (xp_stderr, XP_TEXT("cannot trim %s\n"), argv[1]);
		return -1;
	}

	xp_printf (XP_TEXT("result1: [%s]\n"), buf);

	xxx_trim_unix_path (argv[1]);
	xp_printf (XP_TEXT("result2: [%s]\n"), argv[1]);

#ifdef __linux
	muntrace ();
#endif
	return 0;
}

